package com.NHL.single
{
	import com.NHL.modules.map.vo.MapVo;
	import com.NHL.utils.MapUtil;
	
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.NetStatusEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLRequest;
	
	public class MapLoader extends Loader
	{
		private var _vo:MapVo;
		private static var _inst:MapLoader;
		private var _loadArr:Array;
		private var _result:Function;
		private var _data:Vector.<BitmapData>;
		public static function getInstance():MapLoader
		{
			return _inst||(_inst = new MapLoader);
		}
		
		public function add(vo:MapVo,result:Function):void
		{
			_vo = vo;
			_data = new Vector.<BitmapData>;
			configLoader();
			_loadArr = makeArr();
			_result = result;
			start(_loadArr[0]);
		}
		
		private function start(url:String):void
		{
			load(new URLRequest(url));
		}
		
		private function configLoader():void
		{
			contentLoaderInfo.addEventListener(Event.COMPLETE,onComplete,false,0,true);
			contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,onError,false,0,true);
			contentLoaderInfo.addEventListener(NetStatusEvent.NET_STATUS,onError,false,0,true);
			contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR,onError,false,0,true);
		}
		
		private function onComplete(evt:Event):void
		{
			_loadArr.shift();
			var data:BitmapData  = evt.target.content.bitmapData as BitmapData
			_data.push(data);
			if(_loadArr.length == 0)
			{
				contentLoaderInfo.removeEventListener(Event.COMPLETE,onComplete);
				contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR,onError);
				contentLoaderInfo.removeEventListener(NetStatusEvent.NET_STATUS,onError);
				contentLoaderInfo.removeEventListener(SecurityErrorEvent.SECURITY_ERROR,onError);
				ESource.getInstance().addMap(_vo.id,_data);
				_result();
			}
			else
			{
				start(_loadArr[0]);
			}
		}
		
		private function makeArr():Array
		{
			var purIndex:String = MapUtil.MakeMapURL(_vo.id);
			var arr:Array = new Array();
			var w:int = Math.ceil(_vo.width/_vo.PERWIDTH);
			var h:int = Math.ceil(_vo.height/_vo.PERWIDTH);
			for(var i:int = 0;i<w;i++)
				for(var j:int = 0;j<h;j++)
				{
					var url:String = MapUtil.MakeMapURL(_vo.id)+"_"+i+"_"+j+".png";
					arr.push(url);
				}
			if(arr.length == 0)
				throw new Error("wrong map")
			return arr;	
		}
		
		private function onError(evt:Event):void
		{
			trace("wrong")
		}
	
		public function MapLoader()
		{
			super();
		}
	}
}